package com.techstar.roma.http;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SHA256Util {
	public static String HMACSHA256(String data, String key) throws Exception {
		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
		SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
		sha256_HMAC.init(secret_key);
		byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
		StringBuilder sb = new StringBuilder();
		for (byte item : array) {
			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
		}
		return sb.toString().toUpperCase();

	}

	/**
	 * * 利用java原生的类实现SHA256加密 * @param str 加密后的报文 * @return
	 */
	public static String SHA256(String str) {
		MessageDigest messageDigest;
		String encodestr = "";
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			messageDigest.update(str.getBytes());
			encodestr = byte2Hex(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return encodestr;
	}

	/**
	 * * 将byte转为16进制 * @param bytes * @return
	 */
	private static String byte2Hex(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		String temp = null;
		for (int i = 0; i < bytes.length; i++) {
			temp = Integer.toHexString(bytes[i] & 0xFF);
			if (temp.length() == 1) {
				// 1得到一位的进行补0操作
				stringBuffer.append("0");
			}
			stringBuffer.append(temp);
		}
		return stringBuffer.toString();
	}
	
	public static void main(String[] args) throws Exception {
		String b = "GET\n" + 
				"/index/district_trend/\n" + 
				"dist_id=4553&end_time=2359&start_time=0000\n" + 
				"host:cdde44f91f424f3496b0358d5b2a226c.apic.cn-south-1.huaweicloudapis.com\n" + 
				"x-sdk-date:20210622T084252Z\n" + 
				"\n" + 
				"host;x-sdk-date\n" + 
				"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
		System.out.println(SHA256Util.SHA256(b));
		
		String a = "SDK-HMAC-SHA256\n" + 
				"20210622T084252Z\n" + 
				"dd0f86bf712b076e774265daa0af892a2aca523926770c79ca01c7d735b078c8";
		System.out.println(SHA256Util.HMACSHA256(a,"t0@+#3ueUf919@84i95J6tO$O=CaO50ty29Tb8e=9N#8m2NT$84-gOy.-#LTBj-@"));
	}
}
